package app.controllers.member;

import app.Const;
import app.models.basic.Dict;
import app.models.member.Account;
import app.models.member.Member;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import goja.StringPool;
import goja.encry.DigestsKit;
import goja.encry.EncodeKit;
import goja.kits.base.DateKit;
import goja.mvc.Controller;
import goja.security.goja.SecurityKit;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

/**
 * <p>会员账户设置</p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class AccountController extends Controller {

    /*
    跳转账户设置页面
     */
    public void accountSettings() {
        setAttr("curent", 5);
        Member member = SecurityKit.getLoginUser(getRequest());
        Member show_center = Member.dao.findByIdWithShowCenter(member.getNumber(StringPool.PK_COLUMN).intValue());
        List<Dict> dicts = Dict.dao.risk_tolerance();
        setAttr("dicts",dicts);
        setAttr("show_center", show_center);
        render("account_settings.ftl");
    }

    /*
    跳转修改密码页面
     */
    public void tochangePassword() {
        render("change_password.ftl");
    }

    /*
    修改密码验证
     */
    public void checkedPassword() {
        String password = getPara("old_password");
        String newPassword = getPara("password");
        String rPassword = getPara("rpassword");
        if (Strings.isNullOrEmpty(password) || Strings.isNullOrEmpty(newPassword) || Strings.isNullOrEmpty(rPassword)) {
            renderAjaxError("请输入的信息");
            return;
        }
        if (!newPassword.equals(rPassword)) {
            renderAjaxError("两次输入的密码不同");
            return;
        }
        Member m = SecurityKit.getLoginUser(getRequest());
        m = Member.dao.findbyPhone(m.getStr("phone"));

        boolean matcher = SecurityKit.checkPassword(m.getStr("salt"), m.getStr("password"), password);
        if (matcher) {
            renderAjaxSuccess();
        } else {
            renderAjaxFailure("当前密码不正确");
        }
    }

    /*
    修改登录密码
     */
    public void changePassword() {
        Member m = SecurityKit.getLoginUser(getRequest());
        String password = getPara("password");
        m = Member.dao.findbyPhone(m.getStr("phone"));
        m.generatePassword(password);
        boolean isOk = m.update();
        if (isOk) {
            renderAjaxSuccess();
        } else {
            renderAjaxError("修改失败");

        }
    }

    /*
    跳转修改成功页面
     */
    public void ok() {

    }

    /*
    跳转修改交易密码
     */
    public void toAccountPassword() {
        setAttr("curent", 5);
        Member member = SecurityKit.getLoginUser(getRequest());
        Member show_center = Member.dao.findByIdWithShowCenter(member.getId());
        setAttr("show_center", show_center);
        setAttr("redirect", getPara("redirect"));
        render("change_account_password.ftl");
    }
    /*
    修改交易密码
     */
    public void changeAccountPassword() {
        String oldPassword = getPara("oldpassword");
        String password = getPara("password");
        String rpassword = getPara("rpassword");
        Member member = SecurityKit.getLoginUser(getRequest());
        final BigDecimal id = member.getBigDecimal("id");
        final int memberId = id.intValue();
        final Account account = Account.dao.findbyMember(memberId);
        //验证输入信息
        if (Strings.isNullOrEmpty(oldPassword)) {
            renderAjaxFailure("当前交易密码不能为空");
            return;
        } else if (oldPassword.length() < 6 || oldPassword.length() > 16) {
            renderAjaxFailure("当前交易密码长度6~16位");
            return;
        }
        if (Strings.isNullOrEmpty(password)) {
            renderAjaxFailure("新密码不能为空");
            return;
        } else if (password.length() < 6 || password.length() > 16) {
            renderAjaxFailure("新密码长度6~16位");
            return;
        }
        if (Strings.isNullOrEmpty(rpassword)) {
            renderAjaxFailure("确认密码不能为空");
            return;
        } else if (!rpassword.equals(password)) {
            renderAjaxFailure("确认密码和新密码不一致");
            return;
        }
        boolean matcher = SecurityKit.checkPassword(account.getStr("trade_pwd_salt"),
                account.getStr("trade_pwd"),
                oldPassword);
        if (!matcher) {
            renderAjaxFailure("当前交易密码错误");
            return;
        }
        // 设置交易密码
        byte[] salt = DigestsKit.generateSalt(EncodeKit.SALT_SIZE);
        account.set("trade_pwd_salt", EncodeKit.encodeHex(salt));
        byte[] hashPassword = DigestsKit.sha1(password.getBytes(), salt, EncodeKit.HASH_INTERATIONS);
        account.set("trade_pwd", EncodeKit.encodeHex(hashPassword));
        final Member member1 = Member.dao.findById(memberId);
        // 设置交易密码OK
        member1.set("trade_password_flag", Const.YES);
        final boolean ok = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                return account.update() && member1.update();
            }
        });
        if (ok) {
            renderAjaxSuccess();
        }else{
            renderAjaxFailure("修改失败");
        }
    }

    /*
    设置交易密码
     */
    public void settingAccountPassword(){
        String password = getPara("password");
        String rpassword = getPara("rpassword");
        Member member = SecurityKit.getLoginUser(getRequest());
        final BigDecimal id = member.getBigDecimal("id");
        final int memberId = id.intValue();
        //验证输入信息
        if (Strings.isNullOrEmpty(password)) {
            renderAjaxFailure("新密码不能为空");
            return;
        } else if (password.length() < 6 || password.length() > 16) {
            renderAjaxFailure("新密码长度6~16位");
            return;
        }
        if (Strings.isNullOrEmpty(rpassword)) {
            renderAjaxFailure("确认密码不能为空");
            return;
        } else if (!rpassword.equals(password)) {
            renderAjaxFailure("确认密码和新密码不一致");
            return;
        }
        final Account account = Account.dao.findbyMember(memberId);
        // 设置交易密码
        byte[] salt = DigestsKit.generateSalt(EncodeKit.SALT_SIZE);
        account.set("trade_pwd_salt", EncodeKit.encodeHex(salt));
        byte[] hashPassword = DigestsKit.sha1(password.getBytes(), salt, EncodeKit.HASH_INTERATIONS);
        account.set("trade_pwd", EncodeKit.encodeHex(hashPassword));
        final Member member1 = Member.dao.findById(memberId);
        // 设置交易密码OK
        member1.set("trade_password_flag", Const.YES);
        final boolean ok = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                return account.update() && member1.update();
            }
        });
        if (ok) {
            renderAjaxSuccess();
        }else{
            renderAjaxFailure("设置失败");
        }
    }



    /*
    跳转修改个人资料页面
     */
    public void toUpdateInfo(){
        Member member = SecurityKit.getLoginUser(getRequest());
        Member member1 = Member.dao.findByIdWithShowCenter(member.getNumber(StringPool.PK_COLUMN).intValue());
        setAttr(Const.FIELD_MEMBER,member1);
        render("update.ftl");
    }

    /*
    保存修改的信息
     */
    @Before(POST.class)
    public void update() throws ParseException {
        Member member = SecurityKit.getLoginUser(getRequest());
        Member saveMember = Member.dao.findById(member.getId());
        String birthday = getPara("birthday");
        if (!Strings.isNullOrEmpty(birthday)) {
            saveMember.set("birthday", DateKit.parseDashYMD(birthday));
        }

        String gender = getPara("gender");
        if (!Strings.isNullOrEmpty(gender)) {
            saveMember.set("gender", gender);
        }

        saveMember.set("address", getPara("address"))
                .set("qq", getPara("qq"))
                .set("wxchat", getPara("wxchat"))
                .set("email", getPara("email"))
                .update();
        renderAjaxSuccess();
    }

    /**
     * 检测当前登录人是否设置了交易密码
     */
    public void tradepwd() {
        Member member = SecurityKit.getLoginUser(getRequest());
        Member db_member = Member.dao.findById(member.getId());
        String trade_password_flag = db_member.getStr("trade_password_flag");
        if (!Strings.isNullOrEmpty(trade_password_flag) && StringUtils.equals(trade_password_flag, Const.YES)) {
            renderAjaxSuccess();
        } else {
            renderAjaxFailure();
        }
    }
}
